package com.jcl.cloud.services.unicrawler.config;

import com.jcl.cloud.services.unicrawler.task.CrawlerTaskHandler;
import com.jcl.cloud.services.unicrawler.task.CrawlerTaskHandlerRedisImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableConfigurationProperties(RedisConfigurationProperties.class)
public class CrawlerConfig {

    @Autowired
    private RedisConfigurationProperties redisConfigurationProperties;



    @Bean
    public CrawlerTaskHandler crawlerTaskHandler(JedisPool jedisPool){
        return new CrawlerTaskHandlerRedisImpl(jedisPool,null);
    }



    @Bean(
            destroyMethod = "close"
    )
    public JedisCluster jedisCluster() {
        return null;
    }



    @Bean(
            destroyMethod = "close"
    )
    public JedisPool jedisPool() {
        if (this.redisConfigurationProperties.getAddressList().size() > 1) {
            return null;
        } else {
            String hostPort = (String)this.redisConfigurationProperties.getAddressList().get(0);
            String[] hp = hostPort.split(":");
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(this.redisConfigurationProperties.getMaxTotal());
            config.setMaxIdle(this.redisConfigurationProperties.getMaxIdle());
            config.setMinIdle(this.redisConfigurationProperties.getMinIdle());
            config.setMaxWaitMillis(this.redisConfigurationProperties.getMaxWaitMillis());
            return new JedisPool(config, hp[0], Integer.parseInt(hp[1]), 2000, null, this.redisConfigurationProperties.getDbIndex());
        }
    }
}
